#include "kernel_operator.h"

constexpr int32_t TOTAL_LENGTH = 8 * 2048;                            // total length of data
constexpr int32_t USE_CORE_NUM = 8;                                   // num of core used
constexpr int32_t BLOCK_LENGTH = TOTAL_LENGTH / USE_CORE_NUM;         // length computed of each core
constexpr int32_t TILE_NUM = 8;                                       // split data into 8 tiles for each core
constexpr int32_t BUFFER_NUM = 2;                                     // tensor num for each queue
constexpr int32_t TILE_LENGTH = BLOCK_LENGTH / TILE_NUM / BUFFER_NUM; // separate to 2 parts, due to double buffer

class KernelAtan2 {
public:
    __aicore__ inline KernelAtan2() {}
    __aicore__ inline void Init(GM_ADDR x, GM_ADDR y, GM_ADDR z)
    {
        xGm.SetGlobalBuffer((__gm__ float *)x + BLOCK_LENGTH * AscendC::GetBlockIdx(), BLOCK_LENGTH);
        yGm.SetGlobalBuffer((__gm__ float *)y + BLOCK_LENGTH * AscendC::GetBlockIdx(), BLOCK_LENGTH);
        zGm.SetGlobalBuffer((__gm__ float *)z + BLOCK_LENGTH * AscendC::GetBlockIdx(), BLOCK_LENGTH);
        pipe.InitBuffer(inQueueX, BUFFER_NUM, TILE_LENGTH * sizeof(float));
        pipe.InitBuffer(inQueueY, BUFFER_NUM, TILE_LENGTH * sizeof(float));
        pipe.InitBuffer(outQueueZ, BUFFER_NUM, TILE_LENGTH * sizeof(float));
        
        // 简化临时缓冲区，只保留必要的
        pipe.InitBuffer(ratioBuffer, TILE_LENGTH * sizeof(float));     // y/x 的比值
        pipe.InitBuffer(atanBuffer, TILE_LENGTH * sizeof(float));      // atan(y/x) 的结果
        pipe.InitBuffer(piBuffer, TILE_LENGTH * sizeof(float));        // π 常量
        pipe.InitBuffer(zeroBuffer, TILE_LENGTH * sizeof(float));      // 0 常量
        pipe.InitBuffer(tempBuffer1, TILE_LENGTH * sizeof(float));      // 临时计算结果
        pipe.InitBuffer(tempBuffer2, TILE_LENGTH * sizeof(float));      // 临时储存结果
        pipe.InitBuffer(xNegMask, TILE_LENGTH * sizeof(uint8_t));              // x < 0 掩码
        pipe.InitBuffer(yPosMask, TILE_LENGTH * sizeof(uint8_t));              // y >= 0 掩码
        pipe.InitBuffer(yNegMask, TILE_LENGTH * sizeof(uint8_t));              // y < 0 掩码
        pipe.InitBuffer(quadrant2Mask, TILE_LENGTH * sizeof(uint8_t));         // 第二象限掩码
        pipe.InitBuffer(quadrant3Mask, TILE_LENGTH * sizeof(uint8_t));         // 第三象限掩码
    }
    
    __aicore__ inline void Process()
    {
        int32_t loopCount = TILE_NUM * BUFFER_NUM;
        for (int32_t i = 0; i < loopCount; i++) {
            CopyIn(i);
            Compute(i);
            CopyOut(i);
        }
    }

private:
    __aicore__ inline void CopyIn(int32_t progress)
    {
        AscendC::LocalTensor<float> xLocal = inQueueX.AllocTensor<float>();
        AscendC::LocalTensor<float> yLocal = inQueueY.AllocTensor<float>();
        AscendC::DataCopy(xLocal, xGm[progress * TILE_LENGTH], TILE_LENGTH);
        AscendC::DataCopy(yLocal, yGm[progress * TILE_LENGTH], TILE_LENGTH);
        inQueueX.EnQue(xLocal);
        inQueueY.EnQue(yLocal);
    }
    
    __aicore__ inline void Compute(int32_t progress)
    {
        AscendC::LocalTensor<float> xLocal = inQueueX.DeQue<float>();
        AscendC::LocalTensor<float> yLocal = inQueueY.DeQue<float>();
        AscendC::LocalTensor<float> zLocal = outQueueZ.AllocTensor<float>();
        
        // 获取临时缓冲区
        AscendC::LocalTensor<float> ratio = ratioBuffer.Get<float>();
        AscendC::LocalTensor<float> atan_val = atanBuffer.Get<float>();
        AscendC::LocalTensor<float> pi_tensor = piBuffer.Get<float>();
        AscendC::LocalTensor<float> zero_tensor = zeroBuffer.Get<float>();
        AscendC::LocalTensor<float> temp_calc = tempBuffer1.Get<float>();
        AscendC::LocalTensor<float> temp = tempBuffer2.Get<float>();
        AscendC::LocalTensor<uint8_t> x_neg_mask = xNegMask.Get<uint8_t>();
        AscendC::LocalTensor<uint8_t> y_pos_mask = yPosMask.Get<uint8_t>();
        AscendC::LocalTensor<uint8_t> y_neg_mask = yNegMask.Get<uint8_t>();
        AscendC::LocalTensor<uint8_t> quad2_mask = quadrant2Mask.Get<uint8_t>();
        AscendC::LocalTensor<uint8_t> quad3_mask = quadrant3Mask.Get<uint8_t>();

        // 初始化常量
        const float PI = 3.14159265358979323846f;
        AscendC::Duplicate(zero_tensor, 0.0f, TILE_LENGTH);
        AscendC::Duplicate(pi_tensor, PI, TILE_LENGTH);
        
        // 计算基础 atan(y/x)，这会自动处理无穷大等特殊情况
        AscendC::Div(ratio, yLocal, xLocal, TILE_LENGTH);
        AscendC::Atan(atan_val, ratio, TILE_LENGTH);
        
        // 生成象限判断掩码
        AscendC::CompareScalar(x_neg_mask, xLocal, static_cast<float>(0.0), AscendC::CMPMODE::LT, TILE_LENGTH);   // x < 0
        AscendC::CompareScalar(y_pos_mask, yLocal, static_cast<float>(0.0), AscendC::CMPMODE::GE, TILE_LENGTH);  // y >= 0
        AscendC::CompareScalar(y_neg_mask, yLocal, static_cast<float>(0.0), AscendC::CMPMODE::LT, TILE_LENGTH);   // y < 0
        
        // 第二象限：x < 0 && y >= 0，结果 = atan(y/x) + π
        AscendC::And(quad2_mask, x_neg_mask, y_pos_mask, TILE_LENGTH);
        AscendC::Add(temp_calc, atan_val, pi_tensor, TILE_LENGTH);
        AscendC::Select(temp, quad2_mask, temp_calc, atan_val, AscendC::SELMODE::VSEL_TENSOR_TENSOR_MODE, TILE_LENGTH);
        
        // 第三象限：x < 0 && y < 0，结果 = atan(y/x) - π
        AscendC::And(quad3_mask, x_neg_mask, y_neg_mask, TILE_LENGTH);
        AscendC::Sub(temp_calc, atan_val, pi_tensor, TILE_LENGTH);
        AscendC::Select(zLocal, quad3_mask, temp_calc, temp, AscendC::SELMODE::VSEL_TENSOR_TENSOR_MODE, TILE_LENGTH);

        outQueueZ.EnQue<float>(zLocal);
        inQueueX.FreeTensor(xLocal);
        inQueueY.FreeTensor(yLocal);
    }
    
    __aicore__ inline void CopyOut(int32_t progress)
    {
        AscendC::LocalTensor<float> zLocal = outQueueZ.DeQue<float>();
        AscendC::DataCopy(zGm[progress * TILE_LENGTH], zLocal, TILE_LENGTH);
        outQueueZ.FreeTensor(zLocal);
    }

private:
    AscendC::TPipe pipe;
    AscendC::TQue<AscendC::TPosition::VECIN, BUFFER_NUM> inQueueX, inQueueY;
    AscendC::TQue<AscendC::TPosition::VECOUT, BUFFER_NUM> outQueueZ;
    
    // 简化的临时缓冲区
    AscendC::TBuf<AscendC::QuePosition::VECCALC> ratioBuffer;
    AscendC::TBuf<AscendC::QuePosition::VECCALC> atanBuffer;
    AscendC::TBuf<AscendC::QuePosition::VECCALC> piBuffer;
    AscendC::TBuf<AscendC::QuePosition::VECCALC> zeroBuffer;
    AscendC::TBuf<AscendC::QuePosition::VECCALC> tempBuffer1;
    AscendC::TBuf<AscendC::QuePosition::VECCALC> tempBuffer2;
    AscendC::TBuf<AscendC::QuePosition::VECCALC> xNegMask;
    AscendC::TBuf<AscendC::QuePosition::VECCALC> yPosMask;
    AscendC::TBuf<AscendC::QuePosition::VECCALC> yNegMask;
    AscendC::TBuf<AscendC::QuePosition::VECCALC> quadrant2Mask;
    AscendC::TBuf<AscendC::QuePosition::VECCALC> quadrant3Mask;
    
    AscendC::GlobalTensor<float> xGm;
    AscendC::GlobalTensor<float> yGm;
    AscendC::GlobalTensor<float> zGm;
};

extern "C" __global__ __aicore__ void atan2_custom(GM_ADDR x, GM_ADDR y, GM_ADDR z)
{
    KernelAtan2 op;
    op.Init(x, y, z);
    op.Process();
}

#ifndef ASCENDC_CPU_DEBUG
void atan2_custom_do(uint32_t blockDim, void *stream, uint8_t *x, uint8_t *y, uint8_t *z)
{
    atan2_custom<<<blockDim, nullptr, stream>>>(x, y, z);
}
#endif